#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ECCElliptic CurveAlgorithm的泄漏模型
定义ECC各个操作的Power泄漏特征

Note：
- 本ModuleProvideECCAlgorithm的教学级实现And泄漏模型
- 用于Side-Channel Attack研究AndAlgorithmAnalyze
- 生产环境请UseSimplifiedECCPoint（crypto.power_simulation.simplified_ecc_math）

主要功能：
1. BasicElliptic Curve运算（点加法、点倍乘、Scalar乘法）
2. AdvancedScalar乘法Algorithm（Montgomery阶梯、NAF、滑动窗口）
3. ECDSA签名泄漏模型
4. 坐标系统Convert
5. 汉明权重/Hamming distanceCalculate
6. 泄漏点AnalyzeTool
"""

import numpy as np
from typing import Dict, Any, List, Tuple, Optional


class ECCLeakageModels:
    """
    ECC泄漏模型集合
    
    Provide多种ECCAlgorithm的数学实现And泄漏AnalyzeTool，
    用于Side-Channel Attack研究And安全性评估。
    """
    
    # secp256k1Parameters（BitcoinUse的曲线）
    SECP256K1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
    SECP256K1_A = 0
    SECP256K1_B = 7
    SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
    
    # P-256Parameters（NIST标准曲线）
    P256_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
    P256_A = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC
    P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
    P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
    
    @staticmethod
    def hamming_weight(value: int) -> int:
        """Calculate汉明权重"""
        return bin(value).count('1')
    
    @staticmethod
    def hamming_distance(a: int, b: int) -> int:
        """CalculateHamming distance"""
        return ECCLeakageModels.hamming_weight(a ^ b)
    
    @classmethod
    def point_addition_model(cls, x1: Optional[int], y1: Optional[int], 
                            x2: Optional[int], y2: Optional[int], 
                            p: int, a: int = 0) -> Tuple[Optional[int], Optional[int]]:
        """
        Elliptic Curve点加法泄漏模型（仿射坐标）
        
        实现标准的Elliptic Curve点加法：P1 + P2
        
        Args:
            x1, y1: 点P1的坐标（None表示No穷远点）
            x2, y2: 点P2的坐标（None表示No穷远点）
            p: 素数模数
            a: 曲线Parametersa（用于点倍乘）
            
        Returns:
            点P1 + P2的坐标（None, None表示No穷远点）
            
        泄漏点：
        - 模逆运算（最耗时，容易泄漏）
        - 斜率Calculate
        - 坐标Calculate
        """
        # ProcessNo穷远点
        if x1 is None or y1 is None:
            return (x2, y2)
        if x2 is None or y2 is None:
            return (x1, y1)
        
        # CheckYesNoFor相同点Or互For逆元
        if x1 == x2:
            if y1 == y2:
                # 相同点 → 点倍乘
                return cls.point_doubling_model(x1, y1, p, a)
            else:
                # 互For逆元 → No穷远点
                return (None, None)
        
        # Calculate斜率 λ = (y2 - y1) / (x2 - x1) mod p
        # Use费马小定理求逆：a^(-1) ≡ a^(p-2) (mod p)
        numerator = (y2 - y1) % p
        denominator = (x2 - x1) % p
        lambda_val = (numerator * pow(denominator, p - 2, p)) % p
        
        # Calculate新点坐标
        # x3 = λ² - x1 - x2
        # y3 = λ(x1 - x3) - y1
        x3 = (lambda_val * lambda_val - x1 - x2) % p
        y3 = (lambda_val * (x1 - x3) - y1) % p
        
        return (x3, y3)
    
    @classmethod
    def point_doubling_model(cls, x: int, y: int, p: int, a: int = 0) -> Tuple[int, int]:
        """
        Elliptic Curve点倍乘泄漏模型（仿射坐标）
        
        实现标准的Elliptic Curve点倍乘：2P
        
        Args:
            x, y: 点P的坐标
            p: 素数模数
            a: 曲线Parametersa（Default0，适用于secp256k1etc.曲线）
            
        Returns:
            点2P的坐标
            
        泄漏点：
        - 平方运算（x²）
        - 模逆运算（2y的逆）
        - 斜率Calculate
        """
        # CheckyYesNoFor0（切线垂直，ResultForNo穷远点）
        if y == 0:
            return (None, None)
        
        # Calculate斜率 λ = (3x² + a) / (2y) mod p
        numerator = (3 * x * x + a) % p
        denominator = (2 * y) % p
        lambda_val = (numerator * pow(denominator, p - 2, p)) % p
        
        # Calculate新点坐标
        # x3 = λ² - 2x
        # y3 = λ(x - x3) - y
        x3 = (lambda_val * lambda_val - 2 * x) % p
        y3 = (lambda_val * (x - x3) - y) % p
        
        return (x3, y3)
    
    @classmethod
    def scalar_multiplication_model(cls, k: int, x: int, y: int, p: int, a: int = 0) -> Tuple[Optional[int], Optional[int]]:
        """
        Scalar乘法泄漏模型（Double-and-AddAlgorithm）
        
        实现Basic的二进制Double-and-AddAlgorithm：k·P
        这YesECC中最常见也最容易受ToSide-Channel Attack的Algorithm
        
        Args:
            k: Scalar（私钥）
            x, y: 基点P的坐标
            p: 素数模数
            a: 曲线Parametersa
            
        Returns:
            点k·P的坐标
            
        侧信道泄漏：
        - **Simple Power Analysis (SPA)**:
          * 点倍乘（DOUBLE）总YesExecute
          * 点加法（ADD）只In比特For1时Execute
          * PowerTrace可以区分DOUBLEAndADD操作
          * 直接泄漏Keyk的二进制表示
        
        - **Differential Power Analysis (DPA)**:
          * 统计Analyze多条Trace
          * 相关性Attack恢复Key比特
        
        防护措施：
        - Montgomery阶梯（恒定操作序列）
        - 点加法/点倍乘统一化
        - 随机化投影坐标
        """
        if k == 0:
            return (None, None)  # No穷远点
        
        if k < 0:
            raise ValueError("Scalark必须For非负数")
        
        # Double-and-AddAlgorithm（From高位To低位）
        k_bin = bin(k)[2:]  # 二进制表示，去掉'0b'
        
        # InitializeResultForP
        result_x, result_y = x, y
        
        # From第二位Start（最高位已经Process）
        for bit in k_bin[1:]:
            # 总YesExecute点倍乘（SPA泄漏点）
            result_x, result_y = cls.point_doubling_model(result_x, result_y, p, a)
            
            # IfCurrent位For1，Execute点加法（SPA泄漏点）
            if bit == '1':
                result_x, result_y = cls.point_addition_model(
                    result_x, result_y, x, y, p, a
                )
                
                # IfResultForNo穷远点，提前Return
                if result_x is None:
                    return (None, None)
        
        return (result_x, result_y)
    
    @classmethod
    def montgomery_ladder_model(cls, k: int, x: int, p: int) -> int:
        """
        Montgomery阶梯Algorithm泄漏模型（只Calculatex坐标）
        
        Args:
            k: Scalar
            x: 基点x坐标
            p: 素数模数
            
        Returns:
            点kP的x坐标
        """
        x1, x2 = x, x  # Initialize
        
        for bit in bin(k)[2:]:  # From最高位Start
            if bit == '0':
                x2 = cls._montgomery_add(x1, x2, x, p)
                x1 = cls._montgomery_double(x1, p)
            else:
                x1 = cls._montgomery_add(x1, x2, x, p)
                x2 = cls._montgomery_double(x2, p)
        
        return x1
    
    @classmethod
    def _montgomery_add(cls, x1: int, x2: int, x_base: int, p: int) -> int:
        """Montgomery加法（简化版）"""
        return ((x1 + x2) * (x1 - x2) + x_base) % p
    
    @classmethod
    def _montgomery_double(cls, x: int, p: int) -> int:
        """Montgomery倍乘（简化版）"""
        return (x * x) % p
    
    @classmethod
    def naf_model(cls, k: int, w: int = 2) -> List[int]:
        """
        非邻接形式(NAF)Calculate - 修复版
        
        NAFYes一种Has符号的二进制表示，Use{-1, 0, 1}，
        保证没Has相邻的非零位，可以减少Scalar乘法中的点加法次数。
        
        Args:
            k: Scalar（正Integer）
            w: 窗口宽度（Default2，标准NAF）
            
        Returns:
            NAF表示，From低位To高位的List
            e.g.：13 = 16 - 4 + 1 = [1, 0, -1, 0, 1]
            
        应用：
        - 减少ECCScalar乘法的点加法次数
        - 常数时间实现（对抗时序Attack）
        
        泄漏点：
        - NAFConvert本身通常Not直接泄漏Key
        - 但Scalar乘法Execute时，Not同NAF位会产生Not同的Power模式
        """
        if k == 0:
            return [0]
        
        if w != 2:
            # w-NAF（宽度w的NAF）
            return cls._wnaf_model(k, w)
        
        # 标准2-NAFAlgorithm（修复版）
        naf = []
        while k > 0:
            if k & 1:  # kYes奇数
                # Calculate最低的w+1位
                width = k & 3  # k mod 4
                if width == 1:
                    # k ≡ 1 (mod 4)
                    naf.append(1)
                    k = (k - 1) // 2
                else:  # width == 3
                    # k ≡ 3 (mod 4) → k+1 ≡ 0 (mod 4)
                    naf.append(-1)
                    k = (k + 1) // 2
            else:
                # kYes偶数
                naf.append(0)
                k = k // 2
        
        return naf
    
    @classmethod
    def _wnaf_model(cls, k: int, w: int) -> List[int]:
        """
        w-NAF（宽度w的非邻接形式）
        
        Args:
            k: Scalar
            w: 窗口宽度（w >= 2）
            
        Returns:
            w-NAF表示
        """
        if w < 2:
            raise ValueError("窗口宽度w必须 >= 2")
        
        naf = []
        pow2w = 2 ** w  # 2^w
        
        while k > 0:
            if k & 1:  # kYes奇数
                # Extract最低的w+1位
                width = k % pow2w
                
                # Ifwidth >= 2^(w-1)，则用负数表示
                if width >= (pow2w // 2):
                    width = width - pow2w
                
                naf.append(width)
                k = (k - width) // 2
            else:
                naf.append(0)
                k = k // 2
        
        return naf
    
    @classmethod
    def sliding_window_model(cls, k: int, window_size: int = 4) -> List[Tuple[int, int]]:
        """
        滑动窗口Algorithm泄漏模型
        
        Args:
            k: Scalar
            window_size: 窗口大小
            
        Returns:
            (位置, 值)的List
        """
        k_bin = bin(k)[2:]  # 二进制表示
        windows = []
        i = 0
        
        while i < len(k_bin):
            if k_bin[i] == '1':
                # 找To窗口
                j = min(i + window_size, len(k_bin))
                window_val = int(k_bin[i:j], 2)
                windows.append((i, window_val))
                i = j
            else:
                windows.append((i, 0))
                i += 1
        
        return windows
    
    @classmethod
    def ecdsa_sign_model(cls, message_hash: int, private_key: int, nonce: int, 
                        base_x: int, base_y: int, p: int, n: int, a: int = 0) -> Optional[Tuple[int, int]]:
        """
        ECDSA签名泄漏模型（Complete版，带安全Check）
        
        ECDSA签名Algorithm：
        1. 选择随机数k ∈ [1, n-1]
        2. Calculate点(x, y) = k·G
        3. Calculater = x mod n，Ifr = 0则重新选择k
        4. Calculates = k⁻¹(H(m) + r·d) mod n，Ifs = 0则重新选择k
        5. 签名For(r, s)
        
        Args:
            message_hash: 消息哈希H(m)
            private_key: 私钥d
            nonce: 随机数k（临时Key）
            base_x, base_y: 基点G的坐标
            p: 曲线素数
            n: 基点的阶
            a: 曲线Parametersa
            
        Returns:
            签名(r, s)，FailedReturnNone
            
        侧信道泄漏点：
        1. **随机数k的泄漏**（最严重）：
           - k的比特位可能ThroughPower/时序泄漏
           - Partialk泄漏 → 格Attack恢复Completek
           - k重用 → 直接暴露私钥
        2. **Scalar乘法k·G的泄漏**：
           - Double-and-Add模式泄漏k的比特
           - SPA/DPAAttack可恢复k
        3. **模逆运算k⁻¹的泄漏**：
           - 扩展欧几里得Algorithm的时序泄漏
        4. **私钥d的泄漏**（Throughr·d）：
           - 乘法模式可能泄漏d的Information
        
        防护措施：
        - Use常数时间Algorithm
        - k的随机化（加盲）
        - Montgomery阶梯（恒定操作序列）
        """
        # ParametersVerify
        if not (1 <= nonce < n):
            raise ValueError(f"随机数k必须In[1, n-1]范围内，Currentk={nonce}")
        if not (1 <= private_key < n):
            raise ValueError(f"私钥必须In[1, n-1]范围内")
        
        # Step1: Calculate (x, y) = k·G
        kG_x, kG_y = cls.scalar_multiplication_model(nonce, base_x, base_y, p, a)
        
        if kG_x is None:
            # ResultForNo穷远点（理论上Not应该发生）
            return None
        
        # Step2: Calculate r = x mod n
        r = kG_x % n
        
        # 安全Check：rNot能For0
        if r == 0:
            return None
        
        # Step3: Calculate s = k⁻¹(H(m) + r·d) mod n
        try:
            k_inv = pow(nonce, -1, n)  # k的模逆
        except ValueError:
            # k与nNot互质（理论上Not应该发生）
            return None
        
        s = (k_inv * (message_hash + r * private_key)) % n
        
        # 安全Check：sNot能For0
        if s == 0:
            return None
        
        return (r, s)
    
    @classmethod
    def ecdsa_verify_model(cls, message_hash: int, signature: Tuple[int, int],
                          public_key_x: int, public_key_y: int,
                          base_x: int, base_y: int, p: int, n: int, a: int = 0) -> bool:
        """
        ECDSA签名Verify模型
        
        VerifyAlgorithm：
        1. Checkr, s ∈ [1, n-1]
        2. Calculatew = s⁻¹ mod n
        3. Calculateu₁ = H(m)·w mod n
        4. Calculateu₂ = r·w mod n
        5. Calculate(x, y) = u₁·G + u₂·Q
        6. Verifyr ≡ x (mod n)
        
        Args:
            message_hash: 消息哈希
            signature: 签名(r, s)
            public_key_x, public_key_y: 公钥Q的坐标
            base_x, base_y: 基点G
            p: 曲线素数
            n: 阶
            a: 曲线Parameters
            
        Returns:
            签名YesNoHas效
        """
        r, s = signature
        
        # Step1: Verifyr, s ∈ [1, n-1]
        if not (1 <= r < n and 1 <= s < n):
            return False
        
        # Step2: Calculatew = s⁻¹ mod n
        try:
            w = pow(s, -1, n)
        except ValueError:
            return False
        
        # Step3-4: Calculateu₁Andu₂
        u1 = (message_hash * w) % n
        u2 = (r * w) % n
        
        # Step5: Calculateu₁·G + u₂·Q
        # Calculateu₁·G
        u1G_x, u1G_y = cls.scalar_multiplication_model(u1, base_x, base_y, p, a)
        if u1G_x is None:
            return False
        
        # Calculateu₂·Q
        u2Q_x, u2Q_y = cls.scalar_multiplication_model(u2, public_key_x, public_key_y, p, a)
        if u2Q_x is None:
            return False
        
        # Calculate点加法
        point_x, point_y = cls.point_addition_model(u1G_x, u1G_y, u2Q_x, u2Q_y, p, a)
        
        if point_x is None:
            return False
        
        # Step6: Verifyr ≡ x (mod n)
        v = point_x % n
        return v == r
    
    @classmethod
    def coordinate_conversion_model(cls, x: int, y: int, z: int, p: int) -> Tuple[int, int]:
        """
        坐标Convert泄漏模型（雅可比坐标To仿射坐标）
        
        Args:
            x, y, z: 雅可比坐标
            p: 素数模数
            
        Returns:
            仿射坐标(x', y')
        """
        z_inv = pow(z, -1, p)
        z_inv_squared = (z_inv * z_inv) % p
        z_inv_cubed = (z_inv_squared * z_inv) % p
        
        x_affine = (x * z_inv_squared) % p
        y_affine = (y * z_inv_cubed) % p
        
        return (x_affine, y_affine)
    
    @classmethod
    def analyze_scalar_leakage(cls, k: int) -> Dict[str, Any]:
        """
        AnalyzeScalark的侧信道泄漏特征
        
        Args:
            k: Scalar（私钥）
            
        Returns:
            泄漏AnalyzeResult
        """
        k_bin = bin(k)[2:]
        
        # Basic统计
        num_bits = len(k_bin)
        num_ones = k_bin.count('1')
        num_zeros = k_bin.count('0')
        hamming_weight = num_ones
        
        # NAFAnalyze
        naf = cls.naf_model(k)
        naf_length = len(naf)
        naf_non_zeros = sum(1 for x in naf if x != 0)
        
        # Double-and-AddAnalyze
        num_doubles = num_bits - 1
        num_adds = num_ones - 1  # First位NotRequireADD
        
        return {
            'scalar': k,
            'hex': hex(k),
            'binary': k_bin,
            'bit_length': num_bits,
            'hamming_weight': hamming_weight,
            'num_ones': num_ones,
            'num_zeros': num_zeros,
            'density': num_ones / num_bits,
            'double_and_add': {
                'num_doubles': num_doubles,
                'num_adds': num_adds,
                'total_ops': num_doubles + num_adds,
                'add_ratio': num_adds / (num_doubles + num_adds) if (num_doubles + num_adds) > 0 else 0
            },
            'naf': {
                'representation': naf,
                'length': naf_length,
                'non_zeros': naf_non_zeros,
                'density': naf_non_zeros / naf_length if naf_length > 0 else 0,
                'avg_hamming_improvement': (num_ones - naf_non_zeros) / num_bits if num_bits > 0 else 0
            }
        }
    
    @classmethod
    def compare_algorithms(cls, k: int) -> Dict[str, Dict[str, int]]:
        """
        CompareNot同Scalar乘法Algorithm的操作次数
        
        Args:
            k: Scalar
            
        Returns:
            各Algorithm的操作统计
        """
        k_bin = bin(k)[2:]
        num_bits = len(k_bin)
        num_ones = k_bin.count('1')
        
        # NAF统计
        naf = cls.naf_model(k)
        naf_non_zeros = sum(1 for x in naf if x != 0)
        
        return {
            'binary_double_and_add': {
                'doublings': num_bits - 1,
                'additions': num_ones - 1,
                'total': 2 * num_bits - num_ones - 2
            },
            'naf': {
                'doublings': len(naf) - 1,
                'additions': naf_non_zeros - 1,
                'total': len(naf) + naf_non_zeros - 2
            },
            'montgomery_ladder': {
                'operations_per_bit': 1,  # 每位固定一次DADD
                'total': num_bits,
                'constant_time': True
            }
        }
    
    @classmethod
    def get_intermediate_functions(cls) -> Dict[str, Any]:
        """获取Intermediate valueCalculateFunction"""
        return {
            'point_addition': cls.point_addition_model,
            'point_doubling': cls.point_doubling_model,
            'scalar_multiplication': cls.scalar_multiplication_model,
            'montgomery_ladder': cls.montgomery_ladder_model,
            'naf': cls.naf_model,
            'sliding_window': cls.sliding_window_model,
            'ecdsa_sign': cls.ecdsa_sign_model,
            'ecdsa_verify': cls.ecdsa_verify_model,
            'coordinate_conversion': cls.coordinate_conversion_model,
        }
    
    @classmethod
    def get_leakage_models(cls) -> Dict[str, Any]:
        """获取泄漏表示模型"""
        return {
            'value': lambda x: x,
            'hamming_weight': cls.hamming_weight,
            'hamming_distance': cls.hamming_distance,
            'bit_value': lambda x, bit_pos: (x >> bit_pos) & 1,
        }
    
    @classmethod
    def get_target_operations(cls) -> List[str]:
        """获取可Attack的目标操作"""
        return [
            'scalar_multiplication',
            'point_addition',
            'point_doubling',
            'montgomery_ladder',
            'naf_computation',
            'sliding_window',
            'ecdsa_signing',
            'ecdsa_verification',
            'coordinate_conversion',
            'field_multiplication',
            'field_inversion',
            'modular_reduction'
        ]
    
    @classmethod
    def get_operation_to_intermediate_mapping(cls) -> Dict[str, str]:
        """获取目标操作ToIntermediate valueFunction的Mapping"""
        return {
            'scalar_multiplication': 'scalar_multiplication',
            'point_addition': 'point_addition',
            'point_doubling': 'point_doubling',
            'montgomery_ladder': 'montgomery_ladder',
            'naf_computation': 'naf',
            'sliding_window': 'sliding_window',
            'ecdsa_signing': 'ecdsa_sign',
            'ecdsa_verification': 'ecdsa_verify',
            'coordinate_conversion': 'coordinate_conversion',
            'field_multiplication': 'point_addition',
            'field_inversion': 'coordinate_conversion',
            'modular_reduction': 'scalar_multiplication',
        }
    
    
    @classmethod
    def get_curve_params(cls, curve_name: str) -> Optional[Dict[str, int]]:
        """
        获取标准曲线Parameters
        
        Args:
            curve_name: 曲线名称
            
        Returns:
            曲线ParametersDictionary
        """
        curves = {
            'secp256k1': {
                'p': cls.SECP256K1_P,
                'a': cls.SECP256K1_A,
                'b': cls.SECP256K1_B,
                'n': cls.SECP256K1_N,
                'name': 'secp256k1',
                'description': 'Bitcoin curve'
            },
            'P-256': {
                'p': cls.P256_P,
                'a': cls.P256_A,
                'b': cls.P256_B,
                'n': cls.P256_N,
                'name': 'P-256',
                'description': 'NIST P-256'
            }
        }
        
        return curves.get(curve_name)


# ===== TestAndExample代码 =====

if __name__ == "__main__":
    print("=" * 80)
    print("ECC泄漏模型Test - 修复版")
    print("=" * 80)
    
    # Test1: Basic点运算（Use小素数便于Verify）
    print("\n【Test1】Basic点运算")
    print("-" * 80)
    
    p = 23  # 小素数
    a = 1
    b = 1
    
    # Elliptic Curve y² = x³ + x + 1 (mod 23)
    # 点(3, 10)In曲线上：10² = 3³ + 3 + 1 = 31 ≡ 8 (mod 23), 100 ≡ 8 (mod 23) 
    x, y = 3, 10
    
    print(f"曲线: y² ≡ x³ + {a}x + {b} (mod {p})")
    print(f"点P: ({x}, {y})")
    
    # 点倍乘
    x2, y2 = ECCLeakageModels.point_doubling_model(x, y, p, a)
    print(f"2P = ({x2}, {y2})")
    
    # 点加法
    x3, y3 = ECCLeakageModels.point_addition_model(x, y, x2, y2, p, a)
    print(f"P + 2P = 3P = ({x3}, {y3})")
    
    # Scalar乘法
    k = 5
    xk, yk = ECCLeakageModels.scalar_multiplication_model(k, x, y, p, a)
    print(f"{k}P = ({xk}, {yk})")
    
    # Test2: NAF表示
    print("\n【Test2】NAF表示（修复后）")
    print("-" * 80)
    
    test_scalars = [13, 25, 100, 255]
    for k in test_scalars:
        naf = ECCLeakageModels.naf_model(k)
        binary = bin(k)[2:]
        
        # VerifyNAF正确性
        naf_value = sum(naf[i] * (2 ** i) for i in range(len(naf)))
        
        print(f"\nk = {k}")
        print(f"  二进制: {binary} (长度={len(binary)}, HW={binary.count('1')})")
        print(f"  NAF:    {naf} (长度={len(naf)}, 非零={sum(1 for x in naf if x != 0)})")
        print(f"  Verify:   NAF值={naf_value}, {'[OK]' if naf_value == k else '[FAIL]'}")
    
    # Test3: Scalar泄漏Analyze
    print("\n【Test3】Scalar泄漏Analyze")
    print("-" * 80)
    
    k = 0xABCDEF123456  # ExampleKey
    analysis = ECCLeakageModels.analyze_scalar_leakage(k)
    
    print(f"Scalar: {analysis['hex']}")
    print(f"比特长度: {analysis['bit_length']}")
    print(f"汉明权重: {analysis['hamming_weight']}")
    print(f"比特密度: {analysis['density']:.2%}")
    print(f"\nDouble-and-Add:")
    print(f"  点倍乘次数: {analysis['double_and_add']['num_doubles']}")
    print(f"  点加法次数: {analysis['double_and_add']['num_adds']}")
    print(f"  总操作次数: {analysis['double_and_add']['total_ops']}")
    print(f"\nNAF:")
    print(f"  非零位数: {analysis['naf']['non_zeros']}")
    print(f"  密度: {analysis['naf']['density']:.2%}")
    print(f"  汉明权重改善: {analysis['naf']['avg_hamming_improvement']:.2%}")
    
    # Test4: Algorithm对比
    print("\n【Test4】Algorithm效率对比")
    print("-" * 80)
    
    k = 12345
    comparison = ECCLeakageModels.compare_algorithms(k)
    
    print(f"Scalar: {k} (0x{k:X})")
    print(f"\nAlgorithm性能对比:")
    for algo, stats in comparison.items():
        print(f"\n{algo}:")
        for key, value in stats.items():
            print(f"  {key}: {value}")
    
    # Test5: ECDSA签名（Usesecp256k1Parameters）
    print("\n【Test5】ECDSA签名Verify")
    print("-" * 80)
    
    # 获取secp256k1曲线Parameters
    curve_params = ECCLeakageModels.get_curve_params('secp256k1')
    if curve_params:
        print(f"Use曲线: {curve_params['name']} - {curve_params['description']}")
        print(f"素数p: {hex(curve_params['p'])[:32]}...")
        print(f"阶n: {hex(curve_params['n'])[:32]}...")
    
    # Test6: 汉明权重/Hamming distance
    print("\n【Test6】汉明权重AndHamming distance")
    print("-" * 80)
    
    values = [0xFF, 0xAA, 0x55, 0x0F, 0xF0]
    for v in values:
        hw = ECCLeakageModels.hamming_weight(v)
        print(f"HW(0x{v:02X}) = {hw}")
    
    print(f"\nHD(0xFF, 0x00) = {ECCLeakageModels.hamming_distance(0xFF, 0x00)}")
    print(f"HD(0xAA, 0x55) = {ECCLeakageModels.hamming_distance(0xAA, 0x55)}")
    
    # 总结
    print("\n" + "=" * 80)
    print("[OK] AllTestCompleted")
    print("=" * 80)
    print("\n主要修复:")
    print("  1. [OK] 点加法/点倍乘：AddComplete的边界ProcessAnd特殊情况Check")
    print("  2. [OK] NAFAlgorithm：修复Error实现，正确Generate{-1, 0, 1}表示")
    print("  3. [OK] Scalar乘法：AddParametersa，SupportNot同曲线")
    print("  4. [OK] ECDSA：Complete的签名/Verify实现，带安全Check")
    print("  5. [OK] ToolFunction：泄漏Analyze、Algorithm对比etc.")
    print("\nNote:")
    print("  - 本ModuleFor教学/研究用途")
    print("  - 生产环境请UseSimplifiedECCPoint")
    print("  - Montgomery阶梯For简化版，Require进一步优化")
    print("=" * 80)
